import aiohttp
import asyncio
import json
from datetime import datetime
from config import ZHUQUE_COOKIE, ZHUQUE_CSRF
#  配置区，运行前填好配置
cookie_headers = {
    "Cookie": ZHUQUE_COOKIE,
    "X-Csrf-Token": ZHUQUE_CSRF,
    }

retry_times = 0
#info_counts = {item: 0 for item in prizes3.keys()}

url = "https://zhuque.in/api/gaming/listBet?tab=game"

setmmade = 'list'
async def getgamelist(commade):
    global retry_times
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers=cookie_headers) as response:
                re_message = ""
                if response.status == 200:
                    retry_times = 0
                    json_response = await response.json()
                    if json_response:
                        game_rows = json_response.get("data", {}).get("rows",[])
                        game_number = json_response.get("data", {}).get("total")
                        if commade == 'list':
                            for sublist in game_rows[::-1]:
                                gameID = sublist["id"]
                                gameteam = ""
                                if len(sublist['info']) == 2:
                                    gameteam = f"{sublist['info'][0]} vs {sublist['info'][1]}"
                                else:
                                    gameteam = " 、".join(team for team in sublist['info'])                                 
                                #gameteam2 = sublist["info"][1]
                                gametime = datetime.fromtimestamp(sublist['end_time'])
                                gametime1 = gametime.strftime('%Y-%m-%d %H:%M')
                                gametitle = sublist['title']
                                if len(sublist['_status']) // 2 == 2:
                                    if float(sublist['_status']['rate0']) > 0:
                                        reate0 = f"{float(100) / float(sublist['_status']['rate0']):.2f}"                                        
                                    else:
                                        reate0 = 'Infinity'  
                                        
                                    if float(sublist['_status']['rate1']) > 0:
                                        reate1 = f"{float(100)  / float(sublist['_status']['rate1']):.2f}"                                        
                                    else:
                                        reate1 = 'Infinity' 

                                    gameOdds = f"{reate0} : {reate1}"

                                else:
                                    for i in range(len(sublist['_status']) // 2):
                                        if float(sublist['_status'][f'rate{i}']) > 0:
                                            gameOdds = ' : '.join(f"{float(100) / float(sublist['_status'][f'rate{i}']):.2f}")
                                        else:
                                            gameOdds = ' : '.join(f"Infinity")

                                sum_bonus = sublist["_status"]["sum"]
                                
                                re_message += f"\n\n比赛项目:{gametitle} \n   比赛ID:{gameID} 下注:{gameteam} 时间:{gametime1} 赔率:{gameOdds}  总下注金额:{sum_bonus}"
                        else:
                            if commade:
                                for row in game_rows:
                                    if row['id'] == commade:
                                        game_info = row['info']
                                        re_message = game_info                               
                                
                else:
                    print(f"Request failed with status {response.status}")
                    re_message =  "" 
                return re_message       
    except aiohttp.ClientError as e:
        if retry_times < 10:
            print(f"Client error: {e}")
            return_times += 1 
            await asyncio.sleep(5)            
            return await getgamelist
    except aiohttp.ServerDisconnectedError as e:    
        if retry_times < 10:
            print(f"Server disconnected: {e}")  
            retry_times += 1 
            await asyncio.sleep(5)            
            return await getgamelist    
    except Exception as e:
        print(f"An error occurred: {e}")
        return None  
    
async def main(commade):
    result_message= await getgamelist(commade)  
    return result_message


# 运行主函数
if __name__ == "__main__":
    asyncio.run(main(setmmade))


